package com.zjcode.cdcer.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.chinatechstar.component.commons.entity.MPage;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.service.BaseService;
import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.component.commons.utils.ExcelUtils;
import com.chinatechstar.component.commons.utils.UuidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjcode.cdcer.mapper.CerSysteminitImportInfoMapper;
import com.zjcode.cdcer.model.*;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.config.MConsts.SUB_DETAIL;
import com.zjcode.cdcer.mq.FileImpMQListener;
import com.zjcode.cdcer.pojo.CerSysteminitImportInfo;
import com.zjcode.cdcer.service.*;
import com.zjcode.cdcer.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CerSysteminitImportInfoServiceImpl implements CerSysteminitImportInfoService,
                                                           BaseService {

    @Autowired
    private CerSysteminitImportInfoMapper cerSysteminitImportInfoMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private TkmSysUserService tkmSysUserService;

    @Autowired
    private TkmEndoscopeDiagnoseNounInfoService endoscopeDiagnoseNounInfoService;

    @Autowired
    private TkmSysOrgService tkmSysOrgService;

    @Autowired
    private FileImpMQListener fileImpMQListener;

    @Autowired
    private TkmSysteminitImportInfoService systeminitImportInfoService;


    @Value("${studio.cer-personinfo-file-in-disk}")
    private String cerPersonFileInDisk;

    @Override
    public Map<String, Object> listAllTableData(PageData pageData) {
        String userId = (String) pageData.get("user");
        String extFlag = sysUserService.findUserExtFlag(userId);
        pageData.put("extFlag", extFlag);

        TkmUserOrgAndRegions regionsAndOrg = tkmSysUserService.findUserRegionsAndOrg(userId);

        // 读取区域信息
        pageData = Utils.transitionRegionInfo(pageData);

        MPage mPage = getPageInfo(pageData);
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
            .stream()
            .collect(Collectors.groupingBy(SysDict::getDictType));
        Page<Object> page = PageHelper.startPage(mPage.getCurrentPage(), mPage.getPageSize());
        List<LinkedHashMap<String, Object>> mapList = cerSysteminitImportInfoMapper.listAllTableData(
            pageData);

        keyListMap
            .entrySet()
            .parallelStream()
            .forEach(entry -> {
                // key
                String key = entry.getKey();
                if (key.equals("xb_code")) {
                    key = "sex";
                }
                List<SysDict> dicts = entry.getValue();
                String finalKey = key;
                mapList
                    .stream()
                    .forEach(map -> {
                        Object o = map.get(finalKey);
                        if (o != null) {
                            Optional<SysDict> first = dicts
                                .stream()
                                .filter(sysDict -> sysDict
                                    .getDictValue()
                                    .equals(o.toString()))
                                .findFirst();
                            first.ifPresent(sysDict -> {
                                map.put(finalKey, sysDict.getDictName());
                            });
                        }
                    });
            });

        // 还原内镜诊断
        mapList
            .parallelStream()
            .forEach(map -> {
                String njzd = (String) map.get("njzd");
                if (ObjectUtils.isNotEmpty(njzd)) {
                    List<String> ids = Arrays.asList(njzd.split(","));
                    List<TkmEndoscopeDiagnoseNounInfo> nounInfos = endoscopeDiagnoseNounInfoService.selectByNounIds(
                            ids);
                    if (nounInfos != null) {
                        map.put("njzd",
                                nounInfos
                                        .stream()
                                        .map(each -> each.getName())
                                        .collect(Collectors.joining(",")));
                    } else {
                        map.put("njzd", "");
                    }
                }
            });

        // 身份证, 给身份证加上掩码
        mapList
            .parallelStream()
            .forEach(each -> {
                String sfz = (String) each.get("sfz");
                if (sfz != null) {
                    each.put("sfz", sfz.substring(0, 6) + "********" + sfz.substring(14));
                }
            });

        return PaginationBuilder.buildResult(mapList,
                                             page.getTotal(),
                                             mPage.getCurrentPage(),
                                             mPage.getPageSize());
    }

    @Override
    public JsonObj batchDeletion(PageData pageData) {
        String tradeId = get32UUID();
        log.info("初始数据库临时库,批量删除数据开始, tradeId: {}", tradeId);
        String data = String.valueOf(pageData.get("data"));
        String[] ids = data.split("\\|");
        if (ids.length > 0) {
            cerSysteminitImportInfoMapper.deleteByIdIn(Arrays.asList(ids));
        }
        log.info("初始数据库临时库,批量删除数据结束, tradeId: {},一共删除数据:{}",
                 tradeId,
                 ids.toString());
        return JsonObj.success("删除成功");
    }

    @Override
    public JsonObj oneClickDelete(PageData pageData) {
        String tradeId = get32UUID();
        String userId = (String) pageData.get("user");
        String extFlag = sysUserService.findUserExtFlag(userId);

        log.info("初始数据库临时库,一键删除开始, tradeId: {}", tradeId);
        CerSysteminitImportInfo info = new CerSysteminitImportInfo();
        info.setIsUplpadTimeout(0);
        info.setIsUploaded(0);
        info.setDeleted(0);
        info.setExtFlag(extFlag);
        List<CerSysteminitImportInfo> list = cerSysteminitImportInfoMapper.queryByAll(info);
        // 获取出所有id组成的list
        List<String> ids = list
            .stream()
            .map(each -> each.getId())
            .collect(Collectors.toList());
        // 删除ids对应的数据
        if (!CollectionUtils.isEmpty(ids)) {
            int i = cerSysteminitImportInfoMapper.deleteByIdIn(ids);
            log.info("初始数据库临时库,一键删除了执行完成,{}条数据被删除,tradeId:{}", i, tradeId);
        }
        return JsonObj.success("删除成功");
    }

    @Override
    public List<CerSysteminitImportInfo> getAllNoErrorData(PageData pageData) {
        // 查询没有错误的数据,没有被标记超时的数据,没有上报的数据
        List<CerSysteminitImportInfo> data = cerSysteminitImportInfoMapper.getAllNoErrorData(
            pageData);
        if (CollectionUtils.isEmpty(data)) {
            data = new ArrayList<>();
        }
        return data;
    }

    @Override
    public void updateCerSysteminitImportInfoStatus(PageData pageData) {
        // 标记删除
        pageData.put("deleted", 1);
        // 标记数据无错
        pageData.put("isHaveError", 0);
        // 没有超时上报
        pageData.put("is_uplpad_timeout", 0);
        // 是否上报正式库
        pageData.put("is_uploaded", 1);

        cerSysteminitImportInfoMapper.updateCerSysteminitImportInfoStatus(pageData);
    }

    @Override
    public List<LinkedHashMap<String, Object>> queryAllExportDataBy(PageData pageData) {

        String userId = (String) pageData.get("user");
        String ids = (String) pageData.get("ids");

        // 获取extFlag
        String extFlag = sysUserService.findUserExtFlag(userId);

        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
            .stream()
            .collect(Collectors.groupingBy(SysDict::getDictType));

        // 获取ids
        List<String> idList = new ArrayList<>();
        if (!StringUtils.isEmpty(userId)) {
            idList.addAll(Arrays.asList(ids.split("\\|")));
        }

        List<LinkedHashMap<String, Object>> list = cerSysteminitImportInfoMapper.selectAllByExtFlagAndIdList(
            extFlag,
            idList);

        keyListMap
            .entrySet()
            .parallelStream()
            .forEach(entry -> {
                // key
                String key = entry.getKey();
                if (key.equals("xb_code")) {
                    key = "sex";
                }
                List<SysDict> dicts = entry.getValue();
                String finalKey = key;
                list
                    .stream()
                    .forEach(map -> {
                        Object o = map.get(finalKey);
                        if (o != null) {
                            Optional<SysDict> first = dicts
                                .stream()
                                .filter(sysDict -> sysDict
                                    .getDictValue()
                                    .equals(o.toString()))
                                .findFirst();
                            first.ifPresent(sysDict -> {
                                map.put(finalKey,
                                        Optional
                                            .ofNullable(sysDict.getDictName())
                                            .orElse(""));
                            });
                        }
                    });
            });

        return list;
    }


    private String generateCerDataInitFileSavePath( MultipartFile file, String userId) {
        // 生成新的文件名称
        String fileName =
                DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") + "_" + userId + "_" + file
                        .getOriginalFilename()
                        .substring(0,
                                file
                                        .getOriginalFilename()
                                        .lastIndexOf('.')) + file
                        .getOriginalFilename()
                        .substring(file
                                .getOriginalFilename()
                                .lastIndexOf('.'));

        // 生成文件的存放路径
        // 日期目录
        String dirName = cerPersonFileInDisk + DateFormatUtils.format(new Date(), "yyyyMMdd");
        File dir = new File(dirName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirName + "/" + fileName;
    }

    public File commonImportConfig(MultipartFile file, String userId ){
        File tmpfile = new File(generateCerDataInitFileSavePath(file,userId));
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), tmpfile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return tmpfile;
    }

    @Override
    public JsonObj importGJCerSystemDataInit(MultipartFile file, HttpServletResponse response, String userId) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        File tmpfile =commonImportConfig(file,userId);
        // 解析excel
        List<TkmSystemInitImportDataGJ> list = ExcelImportUtil.importExcel(tmpfile, TkmSystemInitImportDataGJ.class, params);

        // 数据过滤,国家来源的数据默认都是正确的，仅过滤名称为null的
        list = list.stream().filter(each -> StringUtils.isNotEmpty(each.getName()) && !Objects.equals("测试",each.getName())).collect(Collectors.toList());

        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
                .stream()
                .collect(Collectors.groupingBy(SysDict::getDictType));

        // 将TkmSystemInitImportDataGJ转换成TkmSysteminitImportInfo
        List<TkmSysteminitImportInfo> importInfoList = list
                .stream()
                .map(each -> fileImpMQListener.getSysteminitImportInfoByGJ(each,keyListMap))
                .collect(Collectors.toList());

        // 检查是否需要显示诊断详情表
        importInfoList
                .parallelStream()
                .forEach(info -> {
                    Map<String, Boolean> booleanMap = Utils.validateIsHighRisk(info);
                    // 食管详情
                    Boolean sg = booleanMap.get(SUB_DETAIL.SG);
                    info.setIsShowSgDetail(sg ? 1 : 0);
                    // 贲门详情
                    Boolean bm = booleanMap.get(SUB_DETAIL.BM);
                    info.setIsShowBmDetail(bm ? 1 : 0);
                    // 胃详情
                    Boolean wd = booleanMap.get(SUB_DETAIL.WD);
                    info.setIsShowWDetail(wd ? 1 : 0);
                    // 将以上三个详情信息放入extFlag2中
                    String extFlag2 = Arrays
                            .asList(info.getIsShowSgDetail(),
                                    info.getIsShowBmDetail(),
                                    info.getIsShowWDetail())
                            .stream()
                            .map(each -> each.toString())
                            .collect(Collectors.joining("|"));
                    info.setExtFlag2(extFlag2);
                });

        // 执行数据插入前的准备工作
        importInfoList
                .stream()
                .forEach(each -> {
                    each.setId(UuidUtil.get32UUID());
                    each.setCreateBy(userId);
                    each.setDeleted(0);
                    each.setVersion(1);
                    each.setInsertDatetime(new Date(System.currentTimeMillis()));
                    each.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                    // 机构名称 -> 查机构id、机构所在的省市区县的id、extFlag值
                    // 机构名称
                    String institutionName = each.getInstitutionName();
                    SysOrg sysOrg = sysUserService.selectOrgInfoByName(institutionName);

                    if (sysOrg != null) {
                        String extFlag = sysUserService.getUserExtFlag(each,sysOrg);
                        each.setExtFlag(extFlag);
                        String orgId = sysOrg.getId().toString();
                        each.setInstitutionId(orgId);
                        // 设置screening_id
                        //screen_id生成规则,区域id+动态码
                        //规则如下:医院的行政区划(6位)+医院的编号(2位)+年份(2位)+加上医院上报序列号(6位)
                        if (sysOrg.getOrgCode() != null) {
                            //医院的行政区划
                            String regionCode = tkmSysOrgService.getRegionCode(orgId) == null ? ""
                                    : tkmSysOrgService.getRegionCode(orgId);
                            //医院的编号
                            String exFlag2 = tkmSysOrgService.getExFlag2(orgId) == null ? ""
                                    : tkmSysOrgService.getExFlag2(orgId);

                            //年份
                            int year = LocalDate
                                    .now()
                                    .getYear();
                            String yearStr = String.valueOf(year);
                            yearStr = yearStr.substring(yearStr.length() - 2);

                            //医院上报序列号
                            //TODO:此循环不能使用parallelStream(),否则多线程跑会同时未拿到数据然后插入表，达不到预设效果
                            String strNum = fileImpMQListener.getScreenId(orgId);
                            if (StringUtils.isEmpty(strNum)) {
                                fileImpMQListener.insertData(orgId);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + "000001";
                                each.setScreeningId(screenId);
                            } else {
                                fileImpMQListener.updateData(orgId, strNum);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + strNum;
                                each.setScreeningId(screenId);
                            }
                        } else {
                            each.setScreeningId("0000000000000000");
                        }

                        // 将内镜诊断的文字描述转换成对应的数字描述
                        String njzd = each.getNjzd();
                        if (ObjectUtils.isNotEmpty(njzd)) {
                            if (njzd.contains(",")) {
                                List<String> nzjdNounNames = Arrays
                                        .asList(njzd.split(","))
                                        .stream()
                                        .filter(str -> StringUtils.isNotEmpty(str))
                                        .collect(Collectors.toList());
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounNames(
                                        nzjdNounNames);
                                if (!CollectionUtils.isEmpty(infos)) {
                                    njzd = infos
                                            .stream()
                                            .map(tkmEndoscopeDiagnoseNounInfo -> tkmEndoscopeDiagnoseNounInfo.getId())
                                            .collect(Collectors.joining(","));
                                    each.setNjzd(njzd);
                                } else {
                                    each.setNjzd("-1");
                                }
                            } else {
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounName(
                                        njzd);
                                if (infos.size() > 0) {
                                    each.setNjzd(infos
                                            .get(0)
                                            .getId());
                                } else {
                                    each.setNjzd("-1");
                                }
                            }
                        }
                    }
                });

        //导出错误数据
        List<TkmSysteminitImportInfo> fails = importInfoList.stream()
                .filter(each -> StringUtils.isEmpty(each.getExtFlag()) || StringUtils.isEmpty(each.getScreeningId()))
                .collect(Collectors.toList());


        // 再次过滤extFlag为null数据
        importInfoList = importInfoList.stream()
                .filter(each -> StringUtils.isNotEmpty(each.getExtFlag()) && StringUtils.isNotEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        // todo: 此处加入交易编号,以及需要统计出胃镜总量,胃镜总量的计算方式,为当前导入的所有数据的个数
        // todo: 交易号的存在主要是为了找出同一批次下导入的数据,以便于后续的统计
        String tradeNo=UuidUtil.get32UUID();
        String checkCode = LocalDate
                .now()
                .format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        importInfoList
                .forEach(each -> {
                    each.setTradeNo(tradeNo);// 交易号
                    each.setCheckCode(checkCode); // 校验编码
                });

        importInfoList.forEach(each -> {
            log.info(each.toString());
        });
        int count = 0;
        // 执行数据写入
        if (importInfoList.size() > 0) {
            count = systeminitImportInfoService.insertRecords(importInfoList);
            log.info("农癌初始数据上报成功，共{}条数据", count);
//            return JsonObj.success("导入成功"+count+"条数据");
        }
        // 组装表头
        List<String> headList = Arrays.asList("不合格原因",
                "省份",
                "城市",
                "区县",
                "机构名称",
                "姓名",
                "性别",
                "年龄",
                "身份证号",
                "地址",
                "联系电话",
                "门诊号",
                "住院号",
                "内镜诊疗日期",
                "对象来源",
                "内镜号",
                "是否无痛",
                "染色类别",
                "图片数量",
                "是否活检",
                "Hp",
                "Hp检测方法",
                "内镜诊断",
                "内镜诊断医师",
                "内镜审核医师",
                "病理号",
                "病理诊断",
                "食管病理诊断代码",
                "贲门病理诊断代码",
                "胃病理诊断代码",
                "十二指肠病理诊断代码",
                "病理诊断医师",
                "病理审核医师",
                "病理报告日期",
                "导入错误原因");
        try {
            // 导出
            if (fails.size()>0) {
                List<LinkedHashMap<String, Object>> failList =new ArrayList<>();
                List<TkmSystemInitImportDataGJ> finalList = list;
                fails.forEach(each->{
                    finalList.forEach(e->{
                        if (Objects.equals(e.getName(),each.getName())&&Objects.equals(e.getSfz(),each.getSfz())) {
                            failList.add(getLinkedMapByList(e));
                        }
                    });
                });
                String s = ExcelUtils.downloadExcel(headList, failList, "导入失败数据导出", response, cerPersonFileInDisk);
                HashMap<String,Object> res =new HashMap<>();
                res.put("errorFile", s);
                String msg ="导入失败"+fails.size()+"条";
                if (count>0) {
                    msg += "，导入成功"+count+"条数据";
                }
                return JsonObj.success(res,msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonObj.error("错误数据导出失败");
        }
        return JsonObj.success("导入成功"+count+"条数据");
    }

    @Override
    public JsonObj importGJCerSystemDataInitOfficial(MultipartFile file, HttpServletResponse response, String userId) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        File tmpfile =commonImportConfig(file,userId);

        // 解析excel
        List<TkmSystemInitIOfficialmportDataGJ> list = ExcelImportUtil.importExcel(tmpfile, TkmSystemInitIOfficialmportDataGJ.class, params);

        // 数据过滤,国家来源的数据默认都是正确的，仅过滤名称为null的
        list = list.stream().filter(each -> StringUtils.isNotEmpty(each.getName()) && !Objects.equals("测试",each.getName())).collect(Collectors.toList());

        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
                .stream()
                .collect(Collectors.groupingBy(SysDict::getDictType));

        // 将TkmSystemInitImportDataGJ转换成CerDetaildataImportOfficeInfo
        List<CerDetaildataImportOfficeInfo> importInfoList = list
                .stream()
                .map(each -> {
                    CerDetaildataImportOfficeInfo target = fileImpMQListener.getSysteminitOfficialImportInfoByGJ(each,keyListMap);
                    return target;
                })
                .collect(Collectors.toList());

        // todo ：对需要导入的数据进行验证，国家导入来源的不需要校验数据
        // 检查是否需要显示诊断详情表
        importInfoList
                .parallelStream()
                .forEach(info -> {
                    TkmSysteminitImportInfo initInfo=new TkmSysteminitImportInfo();
                    initInfo.setNjzd(info.getNjzd());
                    Map<String, Boolean> booleanMap = Utils.validateIsHighRisk(initInfo);
                    // 食管详情
                    Boolean sg = booleanMap.get(SUB_DETAIL.SG);
                    info.setIsShowSgDetail(sg ? 1 : 0);
                    // 贲门详情
                    Boolean bm = booleanMap.get(SUB_DETAIL.BM);
                    info.setIsShowBmDetail(bm ? 1 : 0);
                    // 胃详情
                    Boolean wd = booleanMap.get(SUB_DETAIL.WD);
                    info.setIsShowWDetail(wd ? 1 : 0);
                    // 将以上三个详情信息放入extFlag2中
                    String extFlag2 = Arrays
                            .asList(info.getIsShowSgDetail(),
                                    info.getIsShowBmDetail(),
                                    info.getIsShowWDetail())
                            .stream()
                            .map(each -> each.toString())
                            .collect(Collectors.joining("|"));
                    info.setExtFlag2(extFlag2);
                });

        // 执行数据插入前的准备工作
        importInfoList
                .stream()
                .forEach(each -> {
                    each.setId(UuidUtil.get32UUID());
                    each.setCreateBy(userId);
                    each.setDeleted(0);
                    each.setVersion(1);
                    each.setInsertDatetime(new Date(System.currentTimeMillis()));
                    each.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                    // 机构名称 -> 查机构id、机构所在的省市区县的id、extFlag值
                    // 机构名称
                    String institutionName = each.getInstitutionName();
                    SysOrg sysOrg = sysUserService.selectOrgInfoByName(institutionName);
                    if (sysOrg != null) {
                        TkmSysteminitImportInfo info =new TkmSysteminitImportInfo();
                        info.setCreateBy(userId);
                        String extFlag = sysUserService.getUserExtFlag(info,sysOrg);
                        each.setProvinceId(info.getProvinceId());
                        each.setCityId(info.getCityId());
                        each.setDistrictId(info.getDistrictId());
                        each.setExtFlag(extFlag);
                        String orgId = sysOrg.getId().toString();
                        each.setInstitutionId(orgId);
                        // 设置screening_id
                        //screen_id生成规则,区域id+动态码
                        //规则如下:医院的行政区划(6位)+医院的编号(2位)+年份(2位)+加上医院上报序列号(6位)
                        if (sysOrg.getOrgCode() != null) {
                            //医院的行政区划
                            String regionCode = tkmSysOrgService.getRegionCode(orgId) == null ? ""
                                    : tkmSysOrgService.getRegionCode(orgId);
                            //医院的编号
                            String exFlag2 = tkmSysOrgService.getExFlag2(orgId) == null ? ""
                                    : tkmSysOrgService.getExFlag2(orgId);

                            //年份
                            int year = LocalDate
                                    .now()
                                    .getYear();
                            String yearStr = String.valueOf(year);
                            yearStr = yearStr.substring(yearStr.length() - 2);

                            //医院上报序列号
                            //TODO:此循环不能使用parallelStream(),否则多线程跑会同时未拿到数据然后插入表，达不到预设效果
                            String strNum = fileImpMQListener.getScreenId(orgId);
                            if (StringUtils.isEmpty(strNum)) {
                                fileImpMQListener.insertData(orgId);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + "000001";
                                each.setScreeningId(screenId);
                            } else {
                                fileImpMQListener.updateData(orgId, strNum);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + strNum;
                                each.setScreeningId(screenId);
                            }
                        } else {
                            each.setScreeningId("0000000000000000");
                        }

                        // 将内镜诊断的文字描述转换成对应的数字描述
                        String njzd = each.getNjzd();
                        if (ObjectUtils.isNotEmpty(njzd)) {
                            if (njzd.contains(",")) {
                                List<String> nzjdNounNames = Arrays
                                        .asList(njzd.split(","))
                                        .stream()
                                        .filter(str -> StringUtils.isNotEmpty(str))
                                        .collect(Collectors.toList());
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounNames(
                                        nzjdNounNames);
                                if (!org.springframework.util.CollectionUtils.isEmpty(infos)) {
                                    njzd = infos
                                            .stream()
                                            .map(tkmEndoscopeDiagnoseNounInfo -> tkmEndoscopeDiagnoseNounInfo.getId())
                                            .collect(Collectors.joining(","));
                                    each.setNjzd(njzd);
                                } else {
                                    each.setNjzd("-1");
                                }
                            } else {
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounName(
                                        njzd);
                                if (infos.size() > 0) {
                                    each.setNjzd(infos
                                            .get(0)
                                            .getId());
                                } else {
                                    each.setNjzd("-1");
                                }
                            }
                        }
                    }
                });

        //导出错误数据
        List<CerDetaildataImportOfficeInfo> fails = importInfoList.stream()
                .filter(each -> StringUtils.isEmpty(each.getExtFlag()) || StringUtils.isEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        // 再次过滤extFlag为null数据
        importInfoList = importInfoList.stream()
                .filter(each -> StringUtils.isNotEmpty(each.getExtFlag())||StringUtils.isNotEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        importInfoList.forEach(each -> {
            log.info(each.toString());
        });
        int count = 0;
        // 执行数据写入
        if (importInfoList.size() > 0) {
            count = systeminitImportInfoService.insertOfficialRecords(importInfoList);
            log.info("导入成功，共{}条数据", count);
        }
        // 组装表头
        List<String> headList = Arrays.asList(
                "省份",
                "城市",
                "区县",
                "机构名称",
                "姓名",
                "性别",
                "年龄",
                "身份证号",
                "地址",
                "联系电话",
                "门诊号",
                "住院号",
                "内镜诊疗日期",
                "对象来源",
                "内镜号",
                "是否无痛",
                "染色类别",
                "图片数量",
                "是否活检",
                "Hp",
                "Hp检测方法",
                "内镜诊断",
                "内镜诊断医师",
                "内镜审核医师",
                "病理号",
                "病理诊断",
                "食管病理诊断代码",
                "贲门病理诊断代码",
                "胃病理诊断代码",
                "十二指肠病理诊断代码",
                "病理诊断医师",
                "病理审核医师",
                "病理报告日期",
                "上传时间",
                "导入错误原因");
        try {
            // 导出
            if (fails.size()>0) {
                List<LinkedHashMap<String, Object>> failList =new ArrayList<>();
                List<TkmSystemInitIOfficialmportDataGJ> finalList = list;
                fails.forEach(each->{
                    finalList.forEach(e->{
                        if (Objects.equals(e.getName(),each.getName())&&Objects.equals(e.getSfz(),each.getSfz())) {
                            failList.add(getLinkedMapByOfficialList(e));
                        }
                    });
                });
                String s = ExcelUtils.downloadExcel(headList, failList, "导入失败数据导出", response, cerPersonFileInDisk);
                HashMap<String,Object> res =new HashMap<>();
                res.put("errorFile", s);
                String msg ="导入失败"+fails.size()+"条";
                if (count>0) {
                    msg += "，导入成功"+count+"条数据";
                }
                return JsonObj.success(res,msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonObj.error("错误数据导出失败");
        }
        return JsonObj.success("导入成功"+count+"条数据");
    }

    @Override
    public JsonObj importGJCerDetailData(MultipartFile file, HttpServletResponse response, String userId) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        File tmpfile =commonImportConfig(file,userId);

        // 解析excel（共用初始上报字段）
        List<TkmSystemInitImportDataGJ> list = ExcelImportUtil.importExcel(tmpfile, TkmSystemInitImportDataGJ.class, params);

        // 数据过滤,国家来源的数据默认都是正确的，仅过滤名称为null的
        list = list.stream().filter(each -> StringUtils.isNotEmpty(each.getName()) && !Objects.equals("测试",each.getName())).collect(Collectors.toList());

        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
                .stream()
                .collect(Collectors.groupingBy(SysDict::getDictType));

        // 将TkmSystemInitImportDataGJ转换成TkmSysteminitImportInfo
        List<TkmSysteminitImportInfo> importInfoList = list
                .stream()
                .map(each -> {
                    TkmSysteminitImportInfo target = fileImpMQListener.getSysteminitImportInfoByGJ(each,keyListMap);
                    return target;
                })
                .collect(Collectors.toList());

        // todo ：对需要导入的数据进行验证，国家导入来源的不需要校验数据

        // 检查是否需要显示诊断详情表
        importInfoList
                .parallelStream()
                .forEach(info -> {
                    Map<String, Boolean> booleanMap = Utils.validateIsHighRisk(info);
                    // 食管详情
                    Boolean sg = booleanMap.get(SUB_DETAIL.SG);
                    info.setIsShowSgDetail(sg ? 1 : 0);
                    // 贲门详情
                    Boolean bm = booleanMap.get(SUB_DETAIL.BM);
                    info.setIsShowBmDetail(bm ? 1 : 0);
                    // 胃详情
                    Boolean wd = booleanMap.get(SUB_DETAIL.WD);
                    info.setIsShowWDetail(wd ? 1 : 0);
                    // 将以上三个详情信息放入extFlag2中
                    String extFlag2 = Arrays
                            .asList(info.getIsShowSgDetail(),
                                    info.getIsShowBmDetail(),
                                    info.getIsShowWDetail())
                            .stream()
                            .map(each -> each.toString())
                            .collect(Collectors.joining("|"));
                    info.setExtFlag2(extFlag2);
                });

        // 执行数据插入前的准备工作
        importInfoList
                .stream()
                .forEach(each -> {
                    each.setId(UuidUtil.get32UUID());
                    each.setCreateBy(userId);
                    each.setDeleted(0);
                    each.setVersion(1);
                    each.setInsertDatetime(new Date(System.currentTimeMillis()));
                    each.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                    // 机构名称 -> 查机构id、机构所在的省市区县的id、extFlag值
                    // 机构名称
                    String institutionName = each.getInstitutionName();
                    SysOrg sysOrg = sysUserService.selectOrgInfoByName(institutionName);

                    if (sysOrg != null) {
                        String extFlag = sysUserService.getUserExtFlag(each,sysOrg);
                        each.setExtFlag(extFlag);
                        String orgId = sysOrg.getId().toString();
                        each.setInstitutionId(orgId);
                        // 设置screening_id
                        //screen_id生成规则,区域id+动态码
                        //规则如下:医院的行政区划(6位)+医院的编号(2位)+年份(2位)+加上医院上报序列号(6位)
                        if (sysOrg.getOrgCode() != null) {
                            //医院的行政区划
                            String regionCode = tkmSysOrgService.getRegionCode(orgId) == null ? ""
                                    : tkmSysOrgService.getRegionCode(orgId);
                            //医院的编号
                            String exFlag2 = tkmSysOrgService.getExFlag2(orgId) == null ? ""
                                    : tkmSysOrgService.getExFlag2(orgId);

                            //年份
                            int year = LocalDate
                                    .now()
                                    .getYear();
                            String yearStr = String.valueOf(year);
                            yearStr = yearStr.substring(yearStr.length() - 2);

                            //医院上报序列号
                            //TODO:此循环不能使用parallelStream(),否则多线程跑会同时未拿到数据然后插入表，达不到预设效果
                            String strNum = fileImpMQListener.getScreenId(orgId);
                            if (StringUtils.isEmpty(strNum)) {
                                fileImpMQListener.insertData(orgId);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + "000001";
                                each.setScreeningId(screenId);
                            } else {
                                fileImpMQListener.updateData(orgId, strNum);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + strNum;
                                each.setScreeningId(screenId);
                            }
                        } else {
                            each.setScreeningId("0000000000000000");
                        }

                        // 将内镜诊断的文字描述转换成对应的数字描述
                        String njzd = each.getNjzd();
                        if (ObjectUtils.isNotEmpty(njzd)) {
                            if (njzd.contains(",")) {
                                List<String> nzjdNounNames = Arrays
                                        .asList(njzd.split(","))
                                        .stream()
                                        .filter(str -> StringUtils.isNotEmpty(str))
                                        .collect(Collectors.toList());
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounNames(
                                        nzjdNounNames);
                                if (!org.springframework.util.CollectionUtils.isEmpty(infos)) {
                                    njzd = infos
                                            .stream()
                                            .map(TkmEndoscopeDiagnoseNounInfo::getId)
                                            .collect(Collectors.joining(","));
                                    each.setNjzd(njzd);
                                } else {
                                    each.setNjzd("-1");
                                }
                            } else {
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounName(
                                        njzd);
                                if (infos.size() > 0) {
                                    each.setNjzd(infos
                                            .get(0)
                                            .getId());
                                } else {
                                    each.setNjzd("-1");
                                }
                            }
                        }
                    }
                });
        //导出错误数据
        List<TkmSysteminitImportInfo> fails = importInfoList.stream()
                .filter(each -> StringUtils.isEmpty(each.getExtFlag()) || StringUtils.isEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        // 再次过滤extFlag为null数据
        importInfoList = importInfoList.stream()
                .filter(each -> StringUtils.isNotEmpty(each.getExtFlag())||StringUtils.isNotEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        importInfoList.forEach(each -> {
            log.info(each.toString());
        });
        int count = 0 ;
        // 执行数据写入
        if (importInfoList.size() > 0) {
            count = systeminitImportInfoService.insertDetailRecords(importInfoList);
            log.info("导入成功，共{}条数据", count);
        }
        // 组装表头
        List<String> headList = Arrays.asList("不合格原因",
                "省份",
                "城市",
                "区县",
                "机构名称",
                "姓名",
                "性别",
                "年龄",
                "身份证号",
                "地址",
                "联系电话",
                "门诊号",
                "住院号",
                "内镜诊疗日期",
                "对象来源",
                "内镜号",
                "是否无痛",
                "染色类别",
                "图片数量",
                "是否活检",
                "Hp",
                "Hp检测方法",
                "内镜诊断",
                "内镜诊断医师",
                "内镜审核医师",
                "病理号",
                "病理诊断",
                "食管病理诊断代码",
                "贲门病理诊断代码",
                "胃病理诊断代码",
                "十二指肠病理诊断代码",
                "病理诊断医师",
                "病理审核医师",
                "病理报告日期",
                "导入错误原因");
        try {
            // 导出
            if (fails.size()>0) {
                List<LinkedHashMap<String, Object>> failList =new ArrayList<>();
                List<TkmSystemInitImportDataGJ> finalList = list;
                fails.forEach(each->{
                    finalList.forEach(e->{
                        if (Objects.equals(e.getName(),each.getName())&&Objects.equals(e.getSfz(),each.getSfz())) {
                            failList.add(getLinkedMapByList(e));
                        }
                    });
                });
                String s = ExcelUtils.downloadExcel(headList, failList, "导入失败数据导出", response, cerPersonFileInDisk);
                HashMap<String,Object> res =new HashMap<>();
                res.put("errorFile", s);
                String msg ="导入失败"+fails.size()+"条";
                if (count>0) {
                    msg += "，导入成功"+count+"条数据";
                }
                return JsonObj.success(res,msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonObj.error("错误数据导出失败");
        }
        return JsonObj.success("导入成功"+count+"条数据");
    }

    @Override
    public JsonObj importGJCerDetailOfficial(MultipartFile file, HttpServletResponse response, String userId) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        File tmpfile =commonImportConfig(file,userId);
        // 解析excel（共用初始正式库字段）
        List<TkmSystemInitIOfficialmportDataGJ> list = ExcelImportUtil.importExcel(tmpfile, TkmSystemInitIOfficialmportDataGJ.class, params);

        // 数据过滤,国家来源的数据默认都是正确的，仅过滤名称为null的
        list = list.stream().filter(each -> StringUtils.isNotEmpty(each.getName()) && !Objects.equals("测试",each.getName())).collect(Collectors.toList());

        // 查询数据自定并分组
        List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
        Map<String, List<SysDict>> keyListMap = allCerDicts
                .stream()
                .collect(Collectors.groupingBy(SysDict::getDictType));

        // 将TkmSystemInitImportDataGJ转换成TkmSysteminitImportInfo
        List<CerDetaildataImportOfficeInfo> importInfoList = list
                .stream()
                .map(each -> {
                    CerDetaildataImportOfficeInfo target = fileImpMQListener.getSysteminitOfficialImportInfoByGJ(each,keyListMap);
                    return target;
                })
                .collect(Collectors.toList());

        // 检查是否需要显示诊断详情表
        importInfoList
                .parallelStream()
                .forEach(info -> {
                    TkmSysteminitImportInfo initInfo=new TkmSysteminitImportInfo();
                    initInfo.setNjzd(info.getNjzd());
                    Map<String, Boolean> booleanMap = Utils.validateIsHighRisk(initInfo);
                    // 食管详情
                    Boolean sg = booleanMap.get(SUB_DETAIL.SG);
                    info.setIsShowSgDetail(sg ? 1 : 0);
                    // 贲门详情
                    Boolean bm = booleanMap.get(SUB_DETAIL.BM);
                    info.setIsShowBmDetail(bm ? 1 : 0);
                    // 胃详情
                    Boolean wd = booleanMap.get(SUB_DETAIL.WD);
                    info.setIsShowWDetail(wd ? 1 : 0);
                    // 将以上三个详情信息放入extFlag2中
                    String extFlag2 = Arrays
                            .asList(info.getIsShowSgDetail(),
                                    info.getIsShowBmDetail(),
                                    info.getIsShowWDetail())
                            .stream()
                            .map(each -> each.toString())
                            .collect(Collectors.joining("|"));
                    info.setExtFlag2(extFlag2);
                });

        // 执行数据插入前的准备工作
        importInfoList
                .stream()
                .forEach(each -> {
                    each.setId(UuidUtil.get32UUID());
                    each.setCreateBy(userId);
                    each.setDeleted(0);
                    each.setVersion(1);
                    each.setInsertDatetime(new Date(System.currentTimeMillis()));
                    each.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
                    // 机构名称 -> 查机构id、机构所在的省市区县的id、extFlag值
                    // 机构名称
                    String institutionName = each.getInstitutionName();
                    SysOrg sysOrg = sysUserService.selectOrgInfoByName(institutionName);

                    if (sysOrg != null) {
                        TkmSysteminitImportInfo info =new TkmSysteminitImportInfo();
                        info.setCreateBy(userId);
                        String extFlag = sysUserService.getUserExtFlag(info,sysOrg);
                        each.setExtFlag(extFlag);
                        String orgId = sysOrg.getId().toString();
                        each.setInstitutionId(orgId);
                        // 设置screening_id
                        //screen_id生成规则,区域id+动态码
                        //规则如下:医院的行政区划(6位)+医院的编号(2位)+年份(2位)+加上医院上报序列号(6位)
                        if (sysOrg.getOrgCode() != null) {
                            //医院的行政区划
                            String regionCode = tkmSysOrgService.getRegionCode(orgId) == null ? ""
                                    : tkmSysOrgService.getRegionCode(orgId);
                            //医院的编号
                            String exFlag2 = tkmSysOrgService.getExFlag2(orgId) == null ? ""
                                    : tkmSysOrgService.getExFlag2(orgId);

                            //年份
                            int year = LocalDate
                                    .now()
                                    .getYear();
                            String yearStr = String.valueOf(year);
                            yearStr = yearStr.substring(yearStr.length() - 2);

                            //医院上报序列号
                            //TODO:此循环不能使用parallelStream(),否则多线程跑会同时未拿到数据然后插入表，达不到预设效果
                            String strNum = fileImpMQListener.getScreenId(orgId);
                            if (StringUtils.isEmpty(strNum)) {
                                fileImpMQListener.insertData(orgId);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + "000001";
                                each.setScreeningId(screenId);
                            } else {
                                fileImpMQListener.updateData(orgId, strNum);
                                //拼接screen_id
                                String screenId = regionCode + exFlag2 + yearStr + strNum;
                                each.setScreeningId(screenId);
                            }
                        } else {
                            each.setScreeningId("0000000000000000");
                        }

                        // 将内镜诊断的文字描述转换成对应的数字描述
                        String njzd = each.getNjzd();
                        if (ObjectUtils.isNotEmpty(njzd)) {
                            if (njzd.contains(",")) {
                                List<String> nzjdNounNames = Arrays
                                        .asList(njzd.split(","))
                                        .stream()
                                        .filter(str -> StringUtils.isNotEmpty(str))
                                        .collect(Collectors.toList());
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounNames(
                                        nzjdNounNames);
                                if (!org.springframework.util.CollectionUtils.isEmpty(infos)) {
                                    njzd = infos
                                            .stream()
                                            .map(tkmEndoscopeDiagnoseNounInfo -> tkmEndoscopeDiagnoseNounInfo.getId())
                                            .collect(Collectors.joining(","));
                                    each.setNjzd(njzd);
                                } else {
                                    each.setNjzd("-1");
                                }
                            } else {
                                List<TkmEndoscopeDiagnoseNounInfo> infos = endoscopeDiagnoseNounInfoService.selectByNounName(
                                        njzd);
                                if (infos.size() > 0) {
                                    each.setNjzd(infos
                                            .get(0)
                                            .getId());
                                } else {
                                    each.setNjzd("-1");
                                }
                            }
                        }
                    }
                });
        //导出错误数据
        List<CerDetaildataImportOfficeInfo> fails = importInfoList.stream()
                .filter(each -> StringUtils.isEmpty(each.getExtFlag()) || StringUtils.isEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        // 再次过滤extFlag为null数据
        importInfoList = importInfoList.stream()
                .filter(each -> StringUtils.isNotEmpty(each.getExtFlag())||StringUtils.isNotEmpty(each.getScreeningId()))
                .collect(Collectors.toList());

        importInfoList.forEach(each -> {
            log.info(each.toString());
        });

        int count = 0;
        // 执行数据写入
        if (importInfoList.size() > 0) {
            count = systeminitImportInfoService.insertDetailOfficials(importInfoList);
            log.info("导入成功，共{}条数据", count);
        }
        // 组装表头
        List<String> headList = Arrays.asList(
                "省份",
                "城市",
                "区县",
                "机构名称",
                "姓名",
                "性别",
                "年龄",
                "身份证号",
                "地址",
                "联系电话",
                "门诊号",
                "住院号",
                "内镜诊疗日期",
                "对象来源",
                "内镜号",
                "是否无痛",
                "染色类别",
                "图片数量",
                "是否活检",
                "Hp",
                "Hp检测方法",
                "内镜诊断",
                "内镜诊断医师",
                "内镜审核医师",
                "病理号",
                "病理诊断",
                "食管病理诊断代码",
                "贲门病理诊断代码",
                "胃病理诊断代码",
                "十二指肠病理诊断代码",
                "病理诊断医师",
                "病理审核医师",
                "病理报告日期",
                "上传时间",
                "导入错误原因");
        try {
            // 导出
            if (fails.size()>0) {
                List<LinkedHashMap<String, Object>> failList =new ArrayList<>();
                List<TkmSystemInitIOfficialmportDataGJ> finalList = list;
                fails.forEach(each->{
                    finalList.forEach(e->{
                        if (Objects.equals(e.getName(),each.getName())&&Objects.equals(e.getSfz(),each.getSfz())) {
                            failList.add(getLinkedMapByOfficialList(e));
                        }
                    });
                });
                String s = ExcelUtils.downloadExcel(headList, failList, "导入失败数据导出", response, cerPersonFileInDisk);
                HashMap<String,Object> res =new HashMap<>();
                res.put("errorFile", s);
                String msg ="导入失败"+fails.size()+"条";
                if (count>0) {
                    msg += "，导入成功"+count+"条数据";
                }
                return JsonObj.success(res,msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonObj.error("错误数据导出失败");
        }
        return JsonObj.success("导入成功"+count+"条数据");
    }

    @Override
    public void exportInitForGJMode(PageData pageData,HttpServletResponse response) {
        String userId = (String) pageData.get("user");
        Object idsData = pageData.get("ids");
        String extFlag = sysUserService.findUserExtFlag(userId);
        pageData.put("extFlag", extFlag);
        List<String> ids = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(idsData)) {
            ids = Arrays.asList(String.valueOf(idsData).split("\\|"));
        }
        // 获取ids
//        List<String> idList = new ArrayList<>();
//        if (!StringUtils.isEmpty(userId)) {
//            idList.addAll(Arrays.asList(ids.split("\\|")));
//        }
        List<LinkedHashMap<String, Object>> list = cerSysteminitImportInfoMapper.selectInitForGJMode(ids,idsData,pageData);
        setCommonExportData(list);
        // 组装表头
        List<String> headList = Arrays.asList("不合格原因",
                "省份",
                "城市",
                "区县",
                "机构名称",
                "姓名",
                "性别",
                "年龄",
                "身份证号",
                "地址",
                "联系电话",
                "门诊号",
                "住院号",
                "内镜诊疗日期",
                "对象来源",
                "内镜号",
                "是否无痛",
                "染色类别",
                "图片数量",
                "是否活检",
                "Hp",
                "Hp检测方法",
                "内镜诊断",
                "内镜诊断医师",
                "内镜审核医师",
                "病理号",
                "病理诊断",
                "食管病理诊断代码",
                "贲门病理诊断代码",
                "胃病理诊断代码",
                "十二指肠病理诊断代码",
                "病理诊断医师",
                "病理审核医师",
                "病理报告日期");
        try {
            // 导出
            ExcelUtils.exportExcel(headList, list, "初始数据导出（国家平台导出模板格式）", response);
        } catch (Exception e) {
            log.info("导入失败，原因：", e);
        }
    }

    @Override
    public void setCommonExportData(List<LinkedHashMap<String, Object>> list){
        if (CollectionUtils.isNotEmpty(list)) {
            // 查询数据自定并分组
            List<SysDict> allCerDicts = sysDictService.findAllCerDicts();
            Map<String, List<SysDict>> keyListMap = allCerDicts
                    .stream()
                    .collect(Collectors.groupingBy(SysDict::getDictType));
            // 还原查询的数字，转成文字描述
            list.forEach(each->{
                keyListMap.entrySet().parallelStream().forEach(item->{
                    String key = item.getKey();
                    List<SysDict> dicts = item.getValue();
                    //xb_code 性别 ：1男、2女
                    if(Objects.equals("xb_code",key)){
                        if (ObjectUtils.isNotEmpty(each.get("sex"))) {
                            Optional<SysDict> first = dicts.stream()
                                    .filter(sysDict -> sysDict.getDictValue().equals(each.get("sex"))).findFirst();
                            first.ifPresent(sysDict -> {
                                each.put("sex",sysDict.getDictName());
                            });
                        }
                    }
                    //zldx_ly 对象来源
                    if(Objects.equals("zldx_ly",key)){
                        if (ObjectUtils.isNotEmpty(each.get("zldx_ly"))) {
                            Optional<SysDict> first = dicts.stream()
                                    .filter(sysDict -> sysDict.getDictValue().equals(each.get("zldx_ly"))).findFirst();
                            first.ifPresent(sysDict -> {
                                each.put("zldx_ly",sysDict.getDictName());
                            });
                        }
                    }
                    //ache 是否无痛
                    if(Objects.equals("ache",key)){
                        if (ObjectUtils.isNotEmpty(each.get("ache"))) {
                            Optional<SysDict> first = dicts.stream()
                                    .filter(sysDict -> sysDict.getDictValue().equals(each.get("ache"))).findFirst();
                            first.ifPresent(sysDict -> {
                                each.put("ache",sysDict.getDictName());
                            });
                        }
                    }
                    //dye 染色类别
                    if(Objects.equals("dye",key)){
                        if (ObjectUtils.isNotEmpty(each.get("dye"))) {
                            Optional<SysDict> first = dicts.stream()
                                    .filter(sysDict -> sysDict.getDictValue().equals(each.get("dye"))).findFirst();
                            first.ifPresent(sysDict -> {
                                each.put("dye",sysDict.getDictName());
                            });
                        }
                    }
                    //is_hj 是否活检
                    if(Objects.equals("is_hj",key)){
                        if (ObjectUtils.isNotEmpty(each.get("is_hj"))) {
                            Optional<SysDict> first = dicts.stream()
                                    .filter(sysDict -> sysDict.getDictValue().equals(each.get("is_hj"))).findFirst();
                            first.ifPresent(sysDict -> {
                                each.put("is_hj",sysDict.getDictName());
                            });
                        }
                    }
                    //Hp hp检测结果
                    if(Objects.equals("Hp",key)){
                        if (ObjectUtils.isNotEmpty(each.get("Hp"))) {
                            Optional<SysDict> first = dicts.stream()
                                    .filter(sysDict -> sysDict.getDictValue().equals(each.get("Hp"))).findFirst();
                            first.ifPresent(sysDict -> {
                                each.put("Hp",sysDict.getDictName());
                            });
                        }
                    }
                    //hpjcjg hp检测方法
                    if(Objects.equals("hpjcjg",key)){
                        if (ObjectUtils.isNotEmpty(each.get("hpjcjg"))) {
                            Optional<SysDict> first = dicts.stream()
                                    .filter(sysDict -> sysDict.getDictValue().equals(each.get("hpjcjg"))).findFirst();
                            first.ifPresent(sysDict -> {
                                each.put("hpjcjg",sysDict.getDictName());
                            });
                        }
                    }
                });
            });

            // 还原内镜诊断
            list.parallelStream()
                .forEach(map -> {
                    String njzd = (String) map.get("njzd");
                    List<String> ids = Arrays.asList(njzd.split(","));
                    List<TkmEndoscopeDiagnoseNounInfo> nounInfos = endoscopeDiagnoseNounInfoService.selectByNounIds(
                            ids);
                    if (nounInfos != null) {
                        map.put("njzd",
                                nounInfos
                                        .stream()
                                        .map(TkmEndoscopeDiagnoseNounInfo::getName)
                                        .collect(Collectors.joining(",")));
                    } else {
                        map.put("njzd", "");
                    }
                });
        }
    }


    private LinkedHashMap<String, Object> getLinkedMapByOfficialList(TkmSystemInitIOfficialmportDataGJ info) {
        LinkedHashMap<String, Object> map=new LinkedHashMap<>();
        map.put("province_name",info.getProvince_name());
        map.put("city_name",info.getCity_name());
        map.put("district_name",info.getDistrict_name());
        map.put("institution_name",info.getInstitution_name());
        map.put("name",info.getName());
        map.put("sex",info.getSex());
        map.put("age",info.getAge());
        map.put("sfz",info.getSfz());
        map.put("addr",info.getAddr());
        map.put("phone",info.getPhone());
        map.put("mzh",info.getMzh());
        map.put("zyh",info.getZyh());
        map.put("blsy_time",info.getNjzl_time());
        map.put("scdx_ly",info.getZldx_ly());
        map.put("nj_num",info.getNj_num());
        map.put("ache",info.getAche());
        map.put("dye",info.getDye());
        map.put("pic_nums",info.getPic_nums());
        map.put("is_hj",info.getIs_hj());
        map.put("Hp",info.getHp());
        map.put("hpjcff",info.getNjzd());
        map.put("njzd",info.getNjzd());
        map.put("nj_staff",info.getNj_staff());
        map.put("verify_staff",info.getVerify_staff());
        map.put("bl_num",info.getBl_num());
        map.put("blzd",info.getBlzd());
        map.put("sgbl_code",info.getSgbl_code());
        map.put("bmbl_code",info.getBmbl_code());
        map.put("wbl_code",info.getWbl_code());
        map.put("sezc_code",info.getSezc_code());
        map.put("blzd_staff",info.getBlzd_staff());
        map.put("blsh_staff",info.getBlsh_staff());
        map.put("blbg_time",info.getBlbg_time());
        map.put("created_at",info.getCreated_at());
        map.put("importError","机构名称系统中不存在");
        return map;
    }

    private LinkedHashMap<String, Object> getLinkedMapByList(TkmSystemInitImportDataGJ info) {
        LinkedHashMap<String, Object> map=new LinkedHashMap<>();
        map.put("errors",info.getErrors());
        map.put("province_name",info.getProvince_name());
        map.put("city_name",info.getCity_name());
        map.put("district_name",info.getDistrict_name());
        map.put("institution_name",info.getInstitution_name());
        map.put("name",info.getName());
        map.put("sex",info.getSex());
        map.put("age",info.getAge());
        map.put("sfz",info.getSfz());
        map.put("addr",info.getAddr());
        map.put("phone",info.getPhone());
        map.put("mzh",info.getMzh());
        map.put("zyh",info.getZyh());
        map.put("blsy_time",info.getBlsy_time());
        map.put("scdx_ly",info.getScdx_ly());
        map.put("nj_num",info.getNj_num());
        map.put("ache",info.getAche());
        map.put("dye",info.getDye());
        map.put("pic_nums",info.getPic_nums());
        map.put("is_hj",info.getIs_hj());
        map.put("Hp",info.getHp());
        map.put("hpjcff",info.getNjzd());
        map.put("njzd",info.getNjzd());
        map.put("nj_staff",info.getNj_staff());
        map.put("verify_staff",info.getVerify_staff());
        map.put("bl_num",info.getBl_num());
        map.put("blzd",info.getBlzd());
        map.put("sgbl_code",info.getSgbl_code());
        map.put("bmbl_code",info.getBmbl_code());
        map.put("wbl_code",info.getWbl_code());
        map.put("sezc_code",info.getSezc_code());
        map.put("blzd_staff",info.getBlzd_staff());
        map.put("blsh_staff",info.getBlsh_staff());
        map.put("blbg_time",info.getBlbg_time());
        map.put("importError","机构名称系统中不存在");
        return map;
    }
}
